package constant.milk.cashbook.widget;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import constant.milk.cashbook.R;
import constant.milk.cashbook.SuperActivity;
import constant.milk.cashbook.bean.BankData;
import constant.milk.cashbook.bean.CheckData;
import constant.milk.cashbook.bean.CreditData;
import constant.milk.cashbook.bean.GiftData;
import constant.milk.cashbook.bean.PhoneData;
import constant.milk.cashbook.bean.RealData;
import constant.milk.cashbook.bean.WidgetSettingData;
import constant.milk.cashbook.database.DBSelectQuery;
import constant.milk.cashbook.database.DbUpdateQuery;
import constant.milk.cashbook.main.MainAssetChoiceActivity;
import constant.milk.cashbook.main.MainAssetListActivity;
import constant.milk.cashbook.main.MainTypeActivity;
import constant.milk.cashbook.tip.TipInfoActivity;
import constant.milk.cashbook.tip.TipMap;
import constant.milk.cashbook.util.MilkManager;
import constant.milk.cashbook.util.MilkUtil;

public class WidgetUpdateActivity extends SuperActivity
{
public static final String WIDGET_SETTING_ID = "WIDGET_SETTING_ID";
	
	private static final int TYPE_REQUEST_CODE = 0;
	private static final int ASSET_REQUEST_CODE = 1;
	private static final int NAME_REQUEST_CODE = 2;
	
	private View typeView;
	private View assetView;
	private View nameView;
	private View kindView;
	
	private TextView typeTextView;
	private TextView assetTextView;
	private TextView nameTextView;
	
	private ArrayList<String> assetNameList;
	
	private Button deleteButton;
	private Button updateButton;
	
	private boolean allFlag;
	private boolean allAssetFlag;
	
	private DBSelectQuery select;
	private MilkManager manager;
	
	private WidgetSettingData data;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.main_update_activity);
		
		setTitle("위젯수정");
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		typeView = findViewById(R.id.mainUpdateTypeView);
		assetView = findViewById(R.id.mainUpdateAssetView);
		nameView = findViewById(R.id.mainUpdateNameView);
		kindView = findViewById(R.id.mainUpdateKindView);
		
		typeTextView = (TextView) findViewById(R.id.mainUpdateTypeTextView);
		assetTextView = (TextView) findViewById(R.id.mainUpdateAssetTextView);
		nameTextView = (TextView) findViewById(R.id.mainUpdateNameTextView);
		
		deleteButton = (Button) findViewById(R.id.deleteButton);
		updateButton = (Button) findViewById(R.id.updateButton);
	}

	@Override
	protected void setOnClick()
	{
		typeView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, MainTypeActivity.class);
				intent.putExtra(MainTypeActivity.MAIN_TYPE_DATA, typeTextView.getText().toString());
				startActivityForResult(intent, TYPE_REQUEST_CODE);
			}
		});
		
		assetView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, MainAssetChoiceActivity.class);
				
				if (typeTextView.getText().toString().equals(getString(R.string.out)))
				{
					intent.putExtra(MainAssetChoiceActivity.INSERT_TYPE, MainAssetChoiceActivity.OUT);
				}
				else if (typeTextView.getText().toString().equals(getString(R.string.in)))
				{
					intent.putExtra(MainAssetChoiceActivity.INSERT_TYPE, MainAssetChoiceActivity.IN);
				}
				else if (typeTextView.getText().toString().equals(getString(R.string.move)))
				{
					intent.putExtra(MainAssetChoiceActivity.INSERT_TYPE, MainAssetChoiceActivity.MOVE);
				}
				else if (typeTextView.getText().toString().equals(getString(R.string.balance)))
				{
					intent.putExtra(MainAssetChoiceActivity.INSERT_TYPE, MainAssetChoiceActivity.BALANCE);
				}
				
				intent.putExtra(MainAssetChoiceActivity.ASSET_CHOICE_DATA, assetTextView.getText().toString());
				startActivityForResult(intent, ASSET_REQUEST_CODE);
			}
		});
		
		nameView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startAssetNameList();
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (!setCheckData())
				{
					return;
				}
				
				if (setUpdateData())
				{
					Intent intent = new Intent(MintWidget.MINT_RECORDE);
					sendBroadcast(intent);
					
					MilkUtil.showDialogFinish(superContext, "확인", 
							"수정에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "잠시후 다시해 주세요.");
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		deleteButton.setVisibility(View.GONE);
		
		manager = new MilkManager(superContext, superDb);
		select = new DBSelectQuery(superContext, superDb);
		
		Intent intent = getIntent();
		String id = intent.getStringExtra(WIDGET_SETTING_ID);
		
		data = select.getWidgetSettingId(id);
				
		typeTextView.setText(manager.getMainId(data.getType()));
		
		assetTextView.setText(manager.getAssetId(data.getAsset()));
		
		if (data.getAsset().equals("6"))
		{
			allFlag = true;
			setAssetNameData(assetTextView.getText().toString());
		}
		else
		{
			allFlag = false;
			setAssetNameData(assetTextView.getText().toString());
			
			if (data.getName().equals(""))
			{
				allAssetFlag = true;
				nameTextView.setText(getString(R.string.all));
			}
			else
			{
				allAssetFlag = true;
				nameTextView.setText(data.getName());
			}
		}
		
		kindView.setVisibility(View.GONE);
	}
	
	private boolean setUpdateData()
	{
		DbUpdateQuery query = null;
		
		try
		{
			query = new DbUpdateQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			map.put("type", manager.getMainStr(typeTextView.getText().toString()));
			
			map.put("asset", manager.getAssetStr(assetTextView.getText().toString()));
			
			if (allFlag)
			{
				map.put("name", "");
			}
			else
			{
				if (allAssetFlag)
				{
					map.put("name", "");
				}
				else
				{
					map.put("name", nameTextView.getText().toString());
				}
			}
			
			query.setWidgetSettingUpdate(map, data.getId());
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	/**
	 * 테이터가 제대로 있는지 확인한다.
	 */
	private boolean setCheckData()
	{
		if (typeTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "타입을 선택해주세요.");
			return false;
		}
		
		if (assetTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "자산을 선택해주세요.");
			return false;
		}
		
		if (nameTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "자산을 추가해주세요.");
			return false;
		}
		
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != Activity.RESULT_OK)
		{
			return;
		}
	
		if (requestCode == TYPE_REQUEST_CODE)
		{
			String str = data.getStringExtra(MainTypeActivity.MAIN_TYPE_DATA);
			typeTextView.setText(str);
		}
		else if (requestCode == ASSET_REQUEST_CODE)
		{
			String str = data.getStringExtra(MainAssetChoiceActivity.ASSET_CHOICE_DATA);
			assetTextView.setText(str);
			
			setAssetNameData(str);
			
			if (str.equals(getString(R.string.all)))
			{
				allFlag = true;
			}
			else
			{
				allFlag = false;
			}
		}
		else if (requestCode == NAME_REQUEST_CODE)
		{
			String str = data.getStringExtra(MainAssetListActivity.ASSET_NAME_DATA);
			
			if (str.equals(""))
			{
				nameTextView.setText(getString(R.string.all));
				allAssetFlag = true;
			}
			else
			{
				nameTextView.setText(str);
				allAssetFlag = false;
			}
		}
	}
	
	private void startAssetNameList()
	{
		if (nameTextView.getText().toString().equals(""))
		{
			MilkUtil.showToast(superContext, "자산을 추가해주세요.");
			return;
		}
		
		Intent intent = new Intent(superContext, MainAssetListActivity.class);
		intent.putExtra(MainAssetListActivity.ASSET_NAME_DATA, nameTextView.getText().toString());
		intent.putExtra(MainAssetListActivity.ASSET_LIST_DATA, assetNameList);
		intent.putExtra(MainAssetListActivity.ASSET_ALL_FLAG, allFlag);
		startActivityForResult(intent, NAME_REQUEST_CODE);
	}
	
	private void setAssetNameData(String str)
	{
		DBSelectQuery query = new DBSelectQuery(superContext, superDb);
		
		assetNameList = new ArrayList<String>();
		
		if (str.equals(getString(R.string.realAsset)))
		{
			ArrayList<RealData> list = query.getRealList();
			
			if (list == null || list.size() < 1)
			{
				nameTextView.setText("");
				nameTextView.setHint("현금을 추가해주세요.");
				return;
			}
			
			nameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.bankAsset)))
		{
			ArrayList<BankData> list = query.getBankList();
			
			if (list == null || list.size() < 1)
			{
				nameTextView.setText("");
				nameTextView.setHint("통장을 추가해주세요.");
				return;
			}
			
			nameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.checkCardAsset)))
		{
			ArrayList<CheckData> list = query.getCheckList();
			
			if (list == null || list.size() < 1)
			{
				nameTextView.setText("");
				nameTextView.setHint("체크카드를 추가해주세요.");
				return;
			}
			
			nameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.creditCardAsset)))
		{
			ArrayList<CreditData> list = query.getCreditList();
			
			if (list == null || list.size() < 1)
			{
				nameTextView.setText("");
				nameTextView.setHint("신용카드를 추가해주세요.");
				return;
			}
			
			nameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.phoneAsset)))
		{
			ArrayList<PhoneData> list = query.getPhoneList();
			
			if (list == null || list.size() < 1)
			{
				nameTextView.setText("");
				nameTextView.setHint("핸드폰을 추가해주세요.");
				return;
			}
			
			nameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.giftCardAsset)))
		{
			ArrayList<GiftData> list = query.getGiftList();
			
			if (list == null || list.size() < 1)
			{
				nameTextView.setText("");
				nameTextView.setHint("상품권을 추가해주세요.");
				return;
			}
			
			nameTextView.setText(list.get(0).getName());
			
			for (int i = 0; i < list.size(); i++)
			{
				assetNameList.add(list.get(i).getName());
			}
		}
		else if (str.equals(getString(R.string.all)))
		{
			nameTextView.setText(getString(R.string.all));
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(superContext, TipInfoActivity.class);
		intent.putExtra(TipInfoActivity.TIP_ID, TipMap.TIP_WIDGET_UPDATE);
		startActivity(intent);
	}

}
